package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;

    @PostMapping
    public Object login(@RequestParam String email, @RequestParam String password){
        JSONResult jsonResult = new JSONResult();
        try {
            User user = userService.login(email, password);

            //将user返回给移动端
            jsonResult.setResult(user);
            //将user恭喜到session中
            UserContext.setCurrentUser(user);

        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }

    @DeleteMapping
    public Object logout(HttpSession session){
        session.invalidate();
        return new JSONResult();
    }
}
